import React, { createContext, useReducer } from 'react';

export interface RcDataType {
  id: number;
  name: string;
  desc?: string;
}
type unNesRcData = {
  [K in keyof RcDataType]?: RcDataType[K];
};
interface RcDataTypeAction extends unNesRcData {
  type: 'add' | 'edit';
}
export const initialData: RcDataType[] = [
  {
    id: 1,
    name: 'aaa',
    desc: '我是a',
  },
];
const reducerTask = (data: RcDataType[], action: RcDataTypeAction) => {
  switch (action.type) {
    case 'add': {
      return [
        ...data,
        {
          id: action.id || 0,
          name: action.name || '',
          desc: action.desc,
        },
      ];
    }
    case 'edit': {
      return data;
    }
    default: {
      return data;
    }
  }
};

export const RcStatesContext = createContext(initialData);
export const RcDispatchContext = createContext(
  {} as React.Dispatch<RcDataTypeAction>,
);

export const RcProvider = ({ children }) => {
  const [data, dispatch] = useReducer(reducerTask, initialData);
  return (
    <RcStatesContext.Provider value={data}>
      <RcDispatchContext.Provider value={dispatch}>
        {children}
      </RcDispatchContext.Provider>
    </RcStatesContext.Provider>
  );
};
